package service

import (
	"log"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"lab.com/define"
	"lab.com/model"
)

func GetpageList(c *gin.Context) {
	size, _ := strconv.Atoi(c.DefaultQuery("size", define.DefaultSize))
	webpage, err := strconv.Atoi(c.DefaultQuery("webpage", define.DefaultPage))
	if err != nil {
		log.Println("GetPageList webpage strconv Error:", err)
		return
	}
	webpage = (webpage - 1) * size
	var count int64
	keyword := c.Query("keyword")

	list := make([]*model.Page, 0)
	tx := model.GetpageList(keyword)
	err = tx.Count(&count).Omit("content").Offset(webpage).Limit(size).Find(&list).Error
	if err != nil {
		log.Println("Get Page List Error:", err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
	//c.String(http.StatusOK, "Get page List")

}

func GetPageDetial(c *gin.Context) {
	identity := c.Query("identity")
	if identity == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "页面唯一标识不能为空",
		})
		return
	}
	page := new(model.Page)
	err := model.DB.Where("identity = ?", identity).First(&page).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			c.JSON(http.StatusOK, gin.H{
				"code": -1,
				"msg":  "页面不存在",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "Get PageDetail Error:" + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": page,
	})
}
